package com.zch.utils.webHook.alarm;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

/**
 * String markdown = new MarkdownContentBuilder()
 *     .text("使用Builder模式构建的内容")
 *     .link("点击这里", "http://example.com")
 *     .build();
 */
@Slf4j
public class FeiShuAlarmMarkdown extends AbstractAlarmMarkdown {
    private static final ObjectMapper objectMapper = new ObjectMapper(); //线程安全的 作为静态成员变量
    private String alarmText;//告警内容
    private String linkText;//超链接显示内容
    private String href;//超链接地址

    //飞书
    public FeiShuAlarmMarkdown buildStyle() {
        this.markdownStyle=MarkdownStyle.FEISHU.name();
        return this;
    }

    //标题
    public FeiShuAlarmMarkdown buildAlarmTitle(String alarmTitle) {
        this.alarmTitle =alarmTitle;
        return this;
    }
    public FeiShuAlarmMarkdown buildEvn(String env) {
        this.env =env;
        return this;
    }
    public FeiShuAlarmMarkdown buildWebHookUrl(String webHookUrl) {
        this.webHookUrl=webHookUrl;
        return this;
    }
    /**
     * 告警内容
     * @param alarmText
     * @return
     */
    public FeiShuAlarmMarkdown buildAlarmText(String alarmText) {
        this.alarmText = alarmText;
        return this;
    }

    /**
     *
     * @param linkText 连接的文案描述
     * @param href 超链接地址
     * @return
     */
    public FeiShuAlarmMarkdown buildLink(String linkText, String href) {
        this.linkText = linkText;
        this.href = href;
        return this;
    }

    public String markdownJson() {
        try{
            ArrayNode arrayNode = objectMapper.createArrayNode();

            if (alarmText != null && !alarmText.isEmpty()) {
                ObjectNode textNode = objectMapper.createObjectNode();
                textNode.put("tag", "text");
                textNode.put("text", alarmText);
                arrayNode.add(textNode);
            }

            if (linkText != null && !linkText.isEmpty() && href != null && !href.isEmpty()) {
                ObjectNode linkNode = objectMapper.createObjectNode();
                linkNode.put("tag", "a");
                linkNode.put("text", linkText);
                linkNode.put("href", href);
                arrayNode.add(linkNode);
            }
            // 将 arrayNode 包装在一个新的 ArrayNode 中
            ArrayNode resultArrayNode = objectMapper.createArrayNode();
            resultArrayNode.add(arrayNode);
            return resultArrayNode.toString();
        }catch (Throwable e){
            log.error("markdownJson error:",e.getMessage(),e);
        }
        return "";
    }

    @Override
    public String getMarkdownJson(){
       return  this.markdownJson();
    }
}
